# 查询商品频道和分类
from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_breadcrumb(category):
    """
    获取面包屑导航
    :param category: 商品类别
    :return: 面包屑导航字典
    """
    breadcrumb = dict(
        category_1='',
        category_2='',
        category_3=''
    )
    if category.parent is None:
        # 当前类别为一级类别
        breadcrumb['category_1'] = category
    elif category.subs.count() == 0:
        # 当前类别为三级
        breadcrumb['category_3'] = category
        cat2 = category.parent
        breadcrumb['category_2'] = cat2
        breadcrumb['category_1'] = cat2.parent
    else:
        # 当前类别为二级
        breadcrumb['category_2'] = category
        breadcrumb['category_1'] = category.parent

    return breadcrumb


def get_categories():
    """
    专门用来获取商品的分类
    之所以放到goods/utils.py中，而不是views中 是因为除了goods应用中的视图以外还有index视图也需要商品的分类，所以就
    封装到此，这样方便其他应用调用
    :return:
    """
    categories = OrderedDict()
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    for channel in channels:  # 总共是11个频道，每个频道中 基本上有3、4个商品类别
        group_id = channel.group_id  # 当前频道的id

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        category_1 = channel.category  # 当前频道的 商品类别

        # 追加当前频道
        categories[group_id]['channels'].append({
            'id': category_1.id,
            'name': category_1.name,
            'url': channel.url
        })
        # 构建当前类别的子类别
        for category_2 in category_1.subs.all():
            category_2.sub_cats = []
            for category_3 in category_2.subs.all():
                category_2.sub_cats.append(category_3)
            categories[group_id]['sub_cats'].append(category_2)

    return categories
